package com.zzh.custom.search;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zzh.custom.R;
import com.zzh.tools.system.ToolScreen;

/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2021-02-03
 * @desc
 */
public class EditSearchView extends ViewGroup {

    private final String TAG_ONE = "1";
    private final String TAG_TWO = "2";

    /**
     * 参数
     */
    private int mSearchSrc;
    private int mEditBg;
    private int mEditColorBg;
    private int mClearSrc;
    private boolean mIsShowClear;
    private boolean mIsShowClose;
    private int mHintColor;
    private String mHint;
    private int mTextColor;
    private int mTextSize;
    private String mText;
    private int mMaxLines;
    private int mCloseTextColor;
    private int mCloseTextSize;
    private boolean mIsShowKeyInput;


    /**
     * view
     */
    private EditText editView;
    private ImageView searchView;
    private ImageView clearView;
    private TextView closeView;

    private TextWatcher mTextWatcher;
    private View.OnClickListener mCloseOnClickListener;


    public EditSearchView(Context context) {
        this(context, null);
    }

    public EditSearchView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public EditSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context, attrs);

    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.EditSearchView, 0, 0);
        mSearchSrc = typeArray.getResourceId(R.styleable.EditSearchView_esSearchSrc, android.R.drawable.ic_menu_search);
        mEditBg = typeArray.getResourceId(R.styleable.EditSearchView_esEditBg, -1);
        mEditColorBg = typeArray.getColor(R.styleable.EditSearchView_esEditColorBg, -1);
        mClearSrc = typeArray.getResourceId(R.styleable.EditSearchView_esClearSrc, android.R.drawable.ic_menu_close_clear_cancel);
        mIsShowClear = typeArray.getBoolean(R.styleable.EditSearchView_esIsShowClear, true);
        mIsShowClose = typeArray.getBoolean(R.styleable.EditSearchView_esIsShowClose, true);
        mHintColor = typeArray.getColor(R.styleable.EditSearchView_esHintColor, Color.GRAY);
        mTextColor = typeArray.getColor(R.styleable.EditSearchView_esTextColor, Color.BLACK);
        mTextSize = typeArray.getDimensionPixelSize(R.styleable.EditSearchView_esTextSize, ToolScreen.dip2px(getContext(), 14));
        mMaxLines = typeArray.getInt(R.styleable.EditSearchView_esMaxLines, 15);
        mCloseTextColor = typeArray.getColor(R.styleable.EditSearchView_esCloseTextColor, Color.BLACK);
        mCloseTextSize = typeArray.getDimensionPixelSize(R.styleable.EditSearchView_esCloseTextSize, ToolScreen.dip2px(getContext(), 16));
        mHint = typeArray.getString(R.styleable.EditSearchView_esHint);
        mText = typeArray.getString(R.styleable.EditSearchView_esText);
        mIsShowKeyInput = typeArray.getBoolean(R.styleable.EditSearchView_esIsShowKeyInput, false);
        typeArray.recycle();
        addView(createView());
        configView();
        configClick();
    }

    private void configClick() {
        editView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (mTextWatcher != null) {
                    mTextWatcher.beforeTextChanged(s, start, count, after);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTextWatcher != null) {
                    mTextWatcher.onTextChanged(s, start, before, count);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mTextWatcher != null) {
                    mTextWatcher.afterTextChanged(s);
                }
                if (mIsShowClear) {
                    Animation animation = clearView.getAnimation();
                    if (s.length() > 0) {
                        if (TextUtils.equals((String) clearView.getTag(), TAG_TWO)) {
                            clearView.setTag(TAG_ONE);
                            if (animation != null) {
                                animation.cancel();
                            }
                            performShowAnimation(clearView);
                        }
                    } else {
                        if (TextUtils.equals((String) clearView.getTag(), TAG_ONE)) {
                            clearView.setTag(TAG_TWO);
                            if (animation != null) {
                                animation.cancel();
                            }
                            performHintAnimation(clearView);
                        }
                    }
                }
            }
        });
        if (mIsShowClear) {
            clearView.setOnClickListener(v -> editView.setText(""));
        }
    }

    private void performHintAnimation(ImageView view) {
        Animation animation = new AlphaAnimation(1, 0);
        animation.setDuration(500);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                view.setClickable(false);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(animation);
    }

    private void performShowAnimation(ImageView view) {
        Animation animation = new AlphaAnimation(0, 1);
        animation.setDuration(500);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setClickable(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(animation);
    }

    private View createView() {
        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.view_edit_search, this, false);
        editView = rootView.findViewById(R.id.edit);
        searchView = rootView.findViewById(R.id.searchTag);
        clearView = rootView.findViewById(R.id.clear);
        closeView = rootView.findViewById(R.id.close);
        return rootView;
    }


    private void configView() {
        editView.setHintTextColor(mHintColor);
        editView.setHint(TextUtils.isEmpty(mHint) ? "请输入" : mHint);
        if (mEditBg != -1) {
            editView.setBackgroundResource(mEditBg);
        } else {
            if (mEditColorBg != -1) {
                editView.setBackgroundColor(mEditColorBg);
            } else {
                editView.setBackground(null);
            }
        }
        editView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLines)});
        editView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        editView.setTextColor(mTextColor);
        editView.setText(TextUtils.isEmpty(mText) ? "" : mText);
        editView.setSelection(editView.getText().toString().length());

        closeView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCloseTextSize);
        closeView.setTextColor(mCloseTextColor);

        searchView.setImageResource(mSearchSrc);

        clearView.setImageResource(mClearSrc);

        clearView.setVisibility(mIsShowClear ? View.INVISIBLE : View.GONE);
        clearView.setTag(TAG_TWO);

        closeView.setVisibility(mIsShowClose ? View.VISIBLE : View.GONE);
        closeView.setOnClickListener(mCloseOnClickListener);

        if (mIsShowKeyInput) {
            editView.postDelayed(() -> showKeyboard(editView), 100);
        }
    }

    public static void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (getMeasuredWidth() <= 0) {
            return;
        }
        int left = getPaddingLeft();
        int right = getPaddingRight();
        int top = getPaddingTop();
        int bottom = getPaddingBottom();

        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);
            childView.layout(
                    left,
                    top,
                    getMeasuredWidth() - left - right,
                    getMeasuredHeight() - top - bottom
            );
        }
    }

    /**
     * 设置文本
     *
     * @param text
     */
    public final void setText(CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            text = "";
        }
        if (editView != null) {
            editView.setText(text);
        } else {
            mText = text.toString();
        }
    }

    /**
     * 设置编辑监听器
     *
     * @param watcher
     */
    public void setTextChangedListener(TextWatcher watcher) {
        mTextWatcher = watcher;
    }

    /**
     * 设置关闭登录
     *
     * @param closeOnClickListener
     */
    public void setCloseOnClickListener(OnClickListener closeOnClickListener) {
        this.mCloseOnClickListener = closeOnClickListener;
        if (closeView != null) {
            closeView.setOnClickListener(mCloseOnClickListener);
        }
    }

    /**
     * 获取编辑的内容
     *
     * @return
     */
    public CharSequence getText() {
        if (editView == null) {
            return "";
        }
        return editView.getText();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }
}
